<?php

declare(strict_types=1);
/**
 * 控制器抽象类
 * 薛原 添加通用接口返回处理逻辑
 * 提供 success 和 fail从控制器返回
 */
namespace App\Controller;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Container\ContainerInterface;

abstract class AbstractController
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @Inject
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var ResponseInterface
     */
    protected $response;

    /**
     * @param array $data
     * @param string $message
     * @return array
     * 统一接口成功格式
     */
    public function success($data = [], $message = 'success') {
        return [
            'code' => 200,
            'message' => $message,
            'data' => $data,
            'timestamp' => time()
        ];
    }

    /**
     * @param int $code
     * @param string $message
     * @param array $data
     * @return array
     * 统一接口失败格式
     */
    public function fail($code = 40002, $message = '请求失败', $data = null) {
        return [
            'code' => $code,
            'message' => $message,
            'data' => $data,
            'errors'=> ($data && isset($data['errors'])?$data['errors']:null),
            'timestamp' => time()
        ];
    }

    public function parseParams(RequestInterface $request)
    {
        $params = json_decode($request->getBody()->getContents(),true);
        return $params;
    }
}
